import { combineReducers } from 'redux'
function CalReducer(state={inputValue:0,time:1,history:'0'},action) {
	
		
			switch(action.type){
				case 'string':
				return {inputValue: doString(action),
						time:state.time+1,
						history:state.history+'\r\r'+action.value+action.actionName+doString(action)};
				default:
				return state
			}
		
	
		
		


function doString(action){
	switch(action.actionName){
		
		case '=':
		 	return doResult(action.value);
		case 'delete':
			return 	action.value.toString().substring(0,action.value.length -1);
		case 'C':
		 return 0;
		 default :
		 return 0;
	}
}
function doResult(input){
	let context = String(input);
	 let index = context.indexOf('+');
	 if(index !== -1){
	 	return doResult(context.substring(0,index)) + doResult(context.substring(index+1));
	 }
	 index = context.lastIndexOf('-');
	 if(index !== -1){
	 	return doResult(context.substring(0,index)) - doResult(context.substring(index+1));
	 }
	 index=context.lastIndexOf('*');
	 if(index !== -1){
	 	return doResult(context.substring(0,index)) * doResult(context.substring(index+1));
	 }
	 index = context.lastIndexOf('/');
	 if(index!== -1){
	 	if(parseInt(context.substring(index+1,index+2),10)===0 || doResult(context.substring(index+1))===0){
	 		alert("被除数不能为0")
	 	}else
	 		return doResult(context.substring(0,index)) / doResult(context.substring(index+1)); 

	 }
	 return parseInt(context,10);
}
}


function CountReducer(state={count:2},action)	{
//因为在connect函数中会对新旧两个state进行浅对比，如果state只是值改变但是引用地址没有改变，connect会认为它们相同而不触发更新

	switch(action.type){
		case 'AddCount':
			return {count:state.count+action.value};
		case 'SubCount':
		    return {count:state.count-action.value};
		default :
			return state;
	}
}
export default combineReducers({
	CalReducer,
	CountReducer
})	